<template>
	<view class="container">
		<view class="head">
			<view class="left">
				<!-- <text>{{ region }}</text> -->
				<!--级联选择器-->
				<uni-data-picker 
					:localdata="areaTree"
					v-slot:default="{data, error, options}" 
					popup-title="请选择所在地区"
					@change="onCityChange"
				>
				    <view v-if="data.length">
						<text>{{ data[data.length - 1].text }}</text>
						<uni-icons type="down" size="15" color="#666"></uni-icons>
				    </view>
				    <view v-else>
						<text>{{ region }}</text>
						<uni-icons type="down" size="15" color="#666"></uni-icons>
				    </view>
				</uni-data-picker>
			</view>
			<view class="right">
				<input 
					type="text" 
					:placeholder="enterText" 
					placeholder-style="font-size: 24rpx;" 
					style="font-size: 26rpx;" 
					confirm-type="search" 
					v-model="keyword"
					@confirm="handlerSearch"
				/>
			</view>
		</view>
		<view class="head-fill">1</view>
		<view class="content">
			<view class="box">
				<view class="box-head">
					搜索结果
				</view>
				<view class="selectable-location-list">
					<view 
						class="selectable-location" 
						v-show="selectableLocationList.length > 0"
						v-for="(item, idx) in selectableLocationList" :key="idx"
						@tap="handlerSelect(item)"
					>
						<view class="left">
							<uni-icons type="location-filled" color="#c00" size="23"></uni-icons>
						</view>
						<view class="right">
							<view class="name">
								{{ item.title }}
							</view>
							<view class="stress">
								{{ item.address }}
							</view>
						</view>
					</view>
					<view class="blank" v-show="selectableLocationList.length === 0">
						{{ blankText }}
					</view>
					<view class="loading-container" v-show="pageIndex > 1">
						<uni-load-more 
							iconType="circle" 
							:status="loadingStatus" 
							:content-text="{contentdown: '上拉加载更多', contentrefresh: '正在加载...', contentnomore: '- 到底了 -'}"
						/>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad, onReachBottom } from '@dcloudio/uni-app'
import { MAP, MAP_KEY } from '@/utils/qq-map-wx.js'
import areaTree from '@/utils/areaTree.js'
import { calcPriceByDistance } from '@/api/order.js'

// current-当前位置，target-目的地
const pageType = ref('target')
const enterText = computed(() => {
	return pageType.value === 'current' ? '请输入当前地址' : '请输入目的地址'
})
const blankText = computed(() => {
	return pageType.value === 'current' ? '请输入当前位置' : '请输入目的位置'
})

// 当前位置
const currLocation = ref({
	latitude: 39.906036,   // 维度
	longitude: 116.397697, // 经度
	altitude: 0,           // 高度
	addressInfo: {
		fullname: '',      // 地址全名
		nation: '',        // 国家
		province: '',      // 省
		city: '',          // 市
		district: '',      // 区
		street: '',        // 街道
		streetNumber: ''   // 街道编号
	}
})

// 页码
const pageIndex = ref(1)
// 当前选中的地区
const region = ref('')
// 是否选择了地区
const selected = ref(false)
// 搜索关键词
const keyword = ref('')

// 可选地址
const selectableLocationList = ref([])
// 加载中
const loadingStatus = ref('loading')

// 切换城市
function onCityChange (e) {
	selected.value = true
	region.value = e.detail.value[e.detail.value.length - 1].value.split(':')[1]
	// console.log(region.value)
}

// 根据 当前地区 和 关键词 搜索
function handlerSearch () {
	if (!keyword.value) {
		return
	}
	// 重置页码
	pageIndex.value = 1
	// 重置加载中
	loadingStatus.value = 'loading'
	// 重置数据
	selectableLocationList.value = []
	uni.showLoading({
		title: '加载中',
		mask: true
	})
	getNextPage().then(() => {
	}).finally(() => {
		uni.hideLoading()
	})
}

// 查询位置
function getNextPage () {
	return new Promise((resolve, reject) => {
		const kwd = selected.value ? region.value + keyword.value : keyword.value
		// console.log(kwd)
		MAP.search({
			page_size: 20,
			page_index: pageIndex.value,
			keyword: kwd,
			success: (res) => {
				// 拼接数据
				selectableLocationList.value = [ ...selectableLocationList.value, ...res.data ]
				// 页码+1
				pageIndex.value++
				// 加载中
				loadingStatus.value = res.data.length < 20 ? 'nomore' : 'loading'
				resolve()
			},
			fail: (err) => {
				console.error(err)
				reject(err)
			}
		})
	})
}

// 选中一个位置 -> 计算距离 -> 计算价格
function handlerSelect (selectedLocation) {
	if (!selectedLocation.id) {
		return
	}
	// 如果选择当前位置，不计算价格，直接返回
	if (pageType.value === 'current'){
		uni.$emit('selected-new-location', {
			location: selectedLocation,
			type: 'current'
		})
		uni.navigateBack()
	} else {
		// 如果选择目的地位置，计算距离和价格
		MAP.direction({
			mode: 'driving',
			from: `${currLocation.value.latitude},${currLocation.value.longitude}`,
			to: `${selectedLocation.location.lat},${selectedLocation.location.lng}`,
			success: (res) => {
				// console.log(res)
				const dist = res.result.routes[0].distance
				const dura = res.result.routes[0].duration
				calcPriceByDistance(Math.ceil(dist / 1000)).then(res => {
					const price = res.data.toFixed(1)
					// 通知下单页面选中新目的地
					uni.$emit('selected-new-location', {
						location: selectedLocation, 
						dist,
						dura,
						price,
						type: 'target'
					})
					// 返回
					uni.navigateBack()
				})
			},
			fail: (err) => {
				console.error(err)
			}
		})
	}
}

// 初始化当前城市和当前位置
onLoad(e => {
	region.value = e.city
	currLocation.value = JSON.parse(e.currLocation)
	// console.log(currLocation.value)
	pageType.value = e.type || 'target'
})
// 触底加载下一页
onReachBottom(() => {
	console.log('触底了')
	getNextPage()
})
</script>

<style lang="scss" scoped>
view {
	box-sizing: border-box;
}
.container {
	width: 100vw;
	height: 100vh;
	// overflow-y: scroll;
	background-color: #f8f8f8;
	.head {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		padding: 0 30rpx;
		height: 80rpx;
		background-color: #f8f8f8;
		display: flex;
		align-items: center;
		.left {
			font-size: 26rpx;
			color: #666;
			display: flex;
			align-items: center;
			justify-content: space-between;
			min-width: 130rpx;
			padding-right: 20rpx;
			border-right: 1rpx solid #ccc;
		}
		.right {
			flex: 1;
			padding-left: 20rpx;
		}
	}
	.head-fill {
		height: 80rpx;
	}
	.content {
		background-color: #f8f8f8;
		overflow-y: scroll;
		padding: 20rpx 30rpx 30rpx 30rpx;
		width: 100%;
		.box {
			width: 100%;
			background-color: #fff;
			border-radius: 20rpx;
			.box-head {
				padding: 20rpx 30rpx;
				font-weight: 600;
				font-size: 28rpx;
				border-bottom: 1rpx solid #eee;
			}
			.selectable-location-list {
				padding: 0 30rpx;
				display: block;
				.blank {
					text-align: center;
					padding: 40rpx 0;
					font-size: 24rpx;
					color: #aaa;
				}
				.loading-container {
					text-align: center;
					padding: 20rpx;
					font-size: 22rpx;
				}
				.selectable-location {
					padding: 20rpx 0;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1rpx solid #eee;
					&:last-child {
						border-bottom: none;
					}
					.left {
						padding: 0 30rpx 0 10rpx;
					}
					.right {
						flex: 1;
						.name {
							font-size: 28rpx;
							font-weight: 600;
						}
						.stress {
							font-size: 21rpx;
							color: #999;
							margin-top: 10rpx;
						}
					}
				}
			}
		}
	}
}

:deep(.uni-load-more__text) {
	font-size: 24rpx;
}
</style>